<template>
  <div class="app-container">
    <a-title />
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="报告名称" prop="reportName">
        <el-input
          type="text"
          v-model.trim="queryParams.reportName"
          placeholder="请输入报告名称"
          clearable
          size="small"
          style="width: 240px"
          @input="change($event)"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报告号" prop="reportNo">
        <el-input
          type="text"
          v-model.trim="queryParams.reportNo"
          placeholder="请输入报告号"
          clearable
          size="small"
          style="width: 240px"
          @input="change($event)"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报告类型" prop="reportType">
        <el-input
          type="text"
          v-model.trim="queryParams.reportType"
          placeholder="请输入报告类型"
          clearable
          size="small"
          style="width: 240px"
          @input="change($event)"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业务名称" prop="businessId">
        <el-select v-model="queryParams.businessId" clearable placeholder="业务名称" :filterable="true" style="width: 240px">
          <el-option
            v-for="item in businessOptionsQuery"
            :key="item.guid"
            :label="item.name"
            :value="item.guid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类别" prop="businessType">
        <el-cascader
          clearable
          v-model="queryParams.businessType"
          :options="categoryOptions"
          :show-all-levels="false"
          :props="{ value: 'id',emitPath:false }"
          filterable
          style="width: 240px"
          placeholder="请选择业务类别"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="createPerson">
        <el-input
          type="text"
          v-model.trim="queryParams.createPerson"
          placeholder="请输入申请人"
          clearable
          size="small"
          style="width: 240px"
          @input="change($event)"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="盖章日期">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="closureStatus">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增报告号</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          
        >导出</el-button>
        <!--v-hasPermi="['system:no:export']" -->
      </el-col>
    </el-row>

    <el-table
      stripe
      v-loading="loading"
      :data="noList"
      :default-sort="{prop: 'createTime', order: 'ascending'}"
      @sort-change="tableSortChange"
    >
      <el-table-column
        label="报告名称"
        align="left"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
        prop="reportName"
        width="260"
      />
      <el-table-column
        label="报告号"
        align="center"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
        prop="reportNo"
        width="150"
      />
      <el-table-column
        label="报告类型"
        align="center"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
        prop="reportType"
      />
      <el-table-column
        label="报告号状态"
        align="center"
        prop="businessStatus"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.businessType" :type="scope.row.statusType" disable-transitions>{{
            scope.row.statusText
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="业务名称"
        align="left"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
        prop="businessName"
        width="260"
      />
      <el-table-column
        label="业务类别"
        align="center"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
        prop="businessType"
      />
      <el-table-column
        label="申请人"
        align="center"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
        prop="createPerson"
      />
      <el-table-column
        label="盖章日期"
        align="center"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
        prop="stampTime"
      >
      <template slot-scope="scope">
            <span>{{ parseTime(scope.row.stampTime,'{y}-{m}-{d} ') }}</span>
          </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报告号对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" @close="cancel">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="业务名称" prop="businessId">
          <el-select
            v-model="business.businessData"
            filterable
            placeholder="请选择业务名称"
            style="width:95%;"
            @change="getShowReportTypeBidding"
          >
            <el-option
              v-for="item in businessOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            />
          </el-select>
          <span class="mustinput">*</span>
        </el-form-item>
        <el-form-item label="报告类型" prop="reportTypeName">
          <el-select v-model="business.reportTypeName" placeholder style="width:95%;">
            <el-option v-for="item in reportTypeOptions" :key="item" :label="item" :value="item" />
          </el-select>
          <span class="mustinput">*</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="refreshData">刷新</el-button>
        <el-button type="primary" @click="submitForm">新增报告号</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import {
  listNo,
  exportNo,
  checkBmsReportNo
} from "@/api/projectWorkbench/projectList/reportNo";
import { listBusinessManagement,checkProject } from "@/api/projectWorkbench/projectList/businessManagement";
import { listNoReportNoList } from "@/api/projectWorkbench/projectList/businessManagement";
import { treeselect } from "@/api/system/business_category";
import aTitle from "@/components/Title";
import { getBpmParams } from "@/api/workflow/workflow";
import { checkProjectStatus } from "@/api/projectWorkbench/projectGlance";

export default {
  name: "reportNo",
  components: { aTitle },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 日期范围
      dateRange: [],
      // 总条数
      total: 0,
      // 报告号表格数据
      noList: [],
      title: undefined,
      open: false,
      categoryOptions: [],
      businessOptionsQuery: [],
      businessOptions: [],
      reportTypeOptions: [],
      //项目结项状态
      closureStatus: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        businessId: undefined,
        type: undefined,
        reportNo: undefined
      },
      business: {
        businessData: "",
        reportTypeName: ""
      }
    };
  },
  created() {
    treeselect().then(res => {
      if (res.code === 200) {
        this.categoryOptions = res.data;
      }
    });

    listBusinessManagement({ projectId: this.$route.params.id }).then(res => {
      if (res.code === 200) {
        this.businessOptionsQuery = res.rows;
      }
    });
    checkProjectStatus(this.$route.params.id).then(res=>{
      if(res.data){
        this.closureStatus = true;
      }
      
    });
    this.getList();
    
  },
  mounted(){
    document.title=document.getElementById("projectNameTitle").innerHTML;
  },
  methods: {
    getBusinessOptions() {
      listNoReportNoList({ projectId: this.$route.params.id }).then(res => {
        if (res.code === 200) {
          this.businessOptions = res.data;
        }
      });
    },
    /** 查询报告号列表 */
    getList() {
      this.loading = true;
      this.queryParams.projectId = this.$route.params.id;
      listNo(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          //this.noList = response.rows;

           this.noList = response.rows.map((item) => {
            if (item.businessStatus === "1") {
              item.statusText = "作废";
              item.statusType = "danger";
            }else{
              if(item.reportNo){
                item.statusText = "有效";
                item.statusType = "success";
              }else{
                if(item.businessType){
                  item.statusText = "申请中";
                  item.statusType = "info";
                }
              }
            
            }

            
            return item;
          });



          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      
      this.queryParams.projectId = this.$route.params.id;
      const queryParams = this.queryParams;
      const dateRange = this.dateRange;
      const addDateRange = this.addDateRange(queryParams, dateRange);
      this.$confirm("是否确认导出所有符合条件的报告号数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportNo(addDateRange);
        })
        .then(response => {
          this.download(response.msg);
        })
        .catch(function() {});
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getBusinessOptions();
      this.open = true;
      this.title = "请选择业务";
    },
    // 表单重置
    reset() {
      this.form = {
        businessId: undefined
      };
      this.resetForm("form");
    },
    //刷新数据
    refreshData() {
      this.business.businessData = undefined;
      this.business.reportTypeName = undefined;
      this.reportTypeOptions = [];
      this.getList();
      this.getBusinessOptions();
    },
    /** 提交按钮 */
    submitForm: function() {
      this.getList();
      if (!this.business.businessData) {
        this.msgError("业务不能为空！");
        return false;
      }
      if (!this.business.reportTypeName) {
        this.msgError("报告类别不能为空！");
        return false;
      }
      
      //判断是否能发起流程
      checkProject(this.$route.params.id,this.business.businessData.split(";")[0]).then(res=>{
        if(res.data===1){
          this.submitFormSec();
        }else{
          this.msgError("本业务已不在服务范围内，不能新增咨询报告号！");
        }
      });
    },
    submitFormSec(){

      var checkParams = {
        businessId: this.business.businessData.split(";")[0],
        reportType: this.business.reportTypeName
      };
      var params = {
        businessTypeId: this.business.businessData.split(";")[1],
        projectId: this.$route.params.id,
        businessId: this.business.businessData.split(";")[0]
      };
      checkBmsReportNo(checkParams).then(res => {
        if (res.code === 200 && res.data === 0) {
          this.getBpmParamsMethod(params);
        } else {
          this.msgInfo(
            "本业务已生成咨询报告号，请勿重复申请！点击刷新按钮重新载入数据！"
          );
        }
      });
    },
    getBpmParamsMethod(params) {
      getBpmParams(params).then(res => {
        if (res.code === 200) {
          this.gotoBpm(
            res.data,
            "consultingReportNumber",
            this.business.reportTypeName
          );
        }
      });
    },
    // 取消按钮
    cancel() {
      this.refreshData();
      this.open = false;
      this.reset();
    },
    gotoBpm(data, item, reportType) {
      this.cancel();
      var bpmUrl = this.bpmUrl;
      var rParam = {
        businessCategoryId: data.businessCategoryId,
        businessCategory: data.businessCategory,
        projectId: data.projectId,
        projectGlobalId:
          data.projectGlobalId == null ? "" : data.projectGlobalId,
        businessId: data.businessId,
        businessName: data.businessName,
        deptId: data.deptId,
        deptName: data.deptName,
        projectLeader: data.projectLeader,
        projectLeaderId: data.projectLeaderId,
        projectName: data.projectName,
        projectManager: data.projectManager,
        projectLeaderNo: data.projectLeaderNo,
        projectManagerNo: data.projectManagerNo,
        projectCode: data.projectCode,
        reportName: data.reportName,
        reportType: reportType,
        reportTypeCounts:this.reportTypeOptions.length
      };
      axios
        .post(bpmUrl + "/Portal/InstanceController/starInstance", rParam)
        .then(function(response) {
          if (response.status == 200 && response.data) {
            var code = JSON.parse(sessionStorage.getItem("userinfo") || {})
              .jobNo;
            //code = Encrypt(code);
            window.open(
              bpmUrl +
                "/Portal/run.html?workflowCode=" +
                item +
                "&formId=" +
                response.data.formId +
                "&date=" +
                response.data.date +
                "&code=" +
                code
            );
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    getShowReportTypeBidding(val) {
      this.businessOptions.forEach(item => {
        if (item.guid === val) {
          this.reportTypeOptions = item.reportTypes;
          this.business.reportTypeName = this.reportTypeOptions[0];
        }
      });
    },
    tableSortChange (column) {
      this.queryParams.pageNum = 1
      if (column.order === 'descending') {
        this.queryParams.sortBy = column.prop
        this.queryParams.order = 'desc';
      } else {
        this.queryParams.sortBy = column.prop
        this.queryParams.order = 'asc';
      }
      this.getList();
    },
    change(e) {
      this.$forceUpdate();
    }
  }
};
</script>